﻿Shader "Unlit/GaussianBlur"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _BlurSize("BlurSize（模糊程度）",Float) = 1.0
    }
    SubShader
    {
        CGINCLUDE
        #include "UnityCG.cginc"
            struct a2v
            {
                float4 vertex : POSITION;
                float2 texcoord : TEXCOORD0;
            };

            struct v2f
            {
                float4 pos : SV_POSITION;
                half2 uv[5] : TEXCOORD0;
            };

            sampler2D _MainTex;
            half4 _MainTex_TexelSize;
            float _BlurSize;

            v2f vertVertical (a2v v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                half2 uv = v.texcoord;
                o.uv[0] = uv;
                o.uv[1] = uv + float2(0.0,_MainTex_TexelSize.y * 1.0) * _BlurSize;
                o.uv[2] = uv - float2(0.0,_MainTex_TexelSize.y * 1.0) * _BlurSize;
                o.uv[3] = uv + float2(0.0,_MainTex_TexelSize.y * 2.0) * _BlurSize;
                o.uv[4] = uv - float2(0.0,_MainTex_TexelSize.y * 2.0) * _BlurSize;
                return o;
            }

            v2f vertHorizontal (a2v v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                half2 uv = v.texcoord;
                o.uv[0] = uv;
                o.uv[1] = uv + float2(_MainTex_TexelSize.x * 1.0 , 0.0) * _BlurSize;
                o.uv[2] = uv - float2(_MainTex_TexelSize.x * 1.0 , 0.0) * _BlurSize;
                o.uv[3] = uv + float2(_MainTex_TexelSize.x * 2.0 , 0.0) * _BlurSize;
                o.uv[4] = uv - float2(_MainTex_TexelSize.x * 2.0 , 0.0) * _BlurSize;
                return o;
            }

            fixed4 fragBlur (v2f i) : SV_Target
            {
                float weight[3] = {0.4026,0.2442,0.0545}; //高斯核权重
                fixed3 sum = tex2D(_MainTex,i.uv[0]).rgb * weight[0];
                for(int k = 1 ; k < 3 ; k++) 
                {
                    sum += tex2D(_MainTex,i.uv[2 * k - 1]).rgb * weight[k];
                    sum += tex2D(_MainTex,i.uv[2 * k]).rgb * weight[k];
                }
                return fixed4(sum,1.0);
            }
        ENDCG

        Tags { "RenderType"="Opaque" }
        LOD 100

        ZTest Always Cull Off ZWrite Off
        Pass
        {
            NAME "GAUSSIAN_BLUR_VERTICAL"
            CGPROGRAM
            #pragma vertex vertVertical
            #pragma fragment fragBlur
            ENDCG
        }
        Pass
        {
            NAME "GAUSSIAN_BLUR_HORIZONTAL"
            CGPROGRAM
            #pragma vertex vertHorizontal
            #pragma fragment fragBlur
            ENDCG
        }
    }
    Fallback Off
}
